
<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
					<el-button type="primary" @click="uploadVisible=true">Excel导入</el-button>
				</el-form-item>
        <el-form-item>
					<el-button type="primary" @click="downloadTemplate">Excel导出</el-button>
				</el-form-item>
<!--        <el-form-item>-->
<!--          <el-upload-->
<!--              class="upload-demo"-->
<!--              action="https://jsonplaceholder.typicode.com/posts/"-->
<!--              :on-preview="handlePreview"-->
<!--              :on-remove="handleRemove"-->
<!--              :before-remove="beforeRemove"-->
<!--              multiple-->
<!--              :limit="3"-->
<!--              :on-exceed="handleExceed"-->
<!--              :file-list="fileList">-->
<!--            <el-button size="small" type="primary">点击上传</el-button>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
			</el-form>
		</el-col>


		<!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工姓名" width="120">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="180">
      </el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="180">
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="180">
<!--      <el-table-column  label="头像" width="180">-->

<!--        <template scope="scope" >-->
<!--          <img src="../../assets/bg1.jpg" height="50" width="180"/>-->
<!--        </template>-->
      </el-table-column>

      <el-table-column prop="age" label="年龄" width="120">
      </el-table-column>
      <el-table-column prop="department.name" label="部门" min-width="80">
      </el-table-column>


      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
            el-pagination:表示分页
            size-change:每页条数改变的时候出发的方法
            @current-change: 当页数改变的时候
           :current-page: 绑定当前页数据
           :page-sizes="[100, 200, 300, 400]" : 每页多少条的选择
           :page-size="100" 每页的条数
           :total="400" 总条数
           layout="total, sizes, prev, pager, next, jumper"
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[3, 5, 27, 50]"
          :page-size="100"
          style="float:right;"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>

		<!--编辑/新增界面-->
		<el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="员工姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="headImage">
          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在部门" prop="department.name">
          <el-select v-model="saveForm.department" placeholder="请选择" clearable value-key="id">
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item">
            </el-option>
          </el-select>

        </el-form-item>


			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

    <!--导入界面-->
    <el-dialog title="导入文件" :visible.sync="uploadVisible" :close-on-click-modal="false">
      <el-upload class="upload-demo" drag action="/api/employee/upload" :on-success="uploadSuccess"
                 :before-upload="beforeAvatarUpload" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
      </el-upload>



<!--      <el-upload-->
<!--          class="upload-demo"-->
<!--          action="https://jsonplaceholder.typicode.com/posts/"-->
<!--          :on-preview="handlePreview"-->
<!--          :on-remove="handleRemove"-->
<!--          :before-remove="beforeRemove"-->
<!--          multiple-->
<!--          :limit="3"-->
<!--          :on-exceed="handleExceed"-->
<!--          :file-list="fileList"-->
<!--          :on-success="uploadSuccess"-->
<!--      >-->
<!--        <el-button size="small" type="primary">点击上传</el-button>-->
<!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
<!--      </el-upload>-->
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="uploadVisible = false">取消</el-button>
        <el-button type="primary" :before-upload="beforeAvatarUpload" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>




    <!--错误数据展示界面-->
    <el-dialog title="无效数据" top="5vh" :visible.sync="failVisible" :close-on-click-modal="true" width="70%">
      <el-table :data="failList" highlight-current-row border style="width: 100%;">
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120" sortable></el-table-column>
        <el-table-column prop="email" label="邮箱" width="240"></el-table-column>
        <el-table-column prop="age" label="年龄" width="160" sortable></el-table-column>
        <el-table-column prop="headImage" label="头像" sortable></el-table-column>
        <el-table-column prop="department.name" label="所属部门" width="160" sortable></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!--<el-button @click.native="failVisible = false">取消</el-button>-->
        <el-button type="primary" @click.native="download">导出</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>


	export default {
		data() {
			return {
        departments:[],
        deptTree:[],
        search: {
					keyword: '',
          currentPage:1,
          pageSize:10
				},
        pageInfo:{
          list: [],
          total: 0
        },
				page: 1,
				listLoading: false,
				sels: [],//列表选中列
				saveFormVisible: false,//编辑界面是否显示
        // excelInputVisible:false,
				editLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				saveForm: {
					id: null,
					username: '',
          email:'',
          department:{
            id: null,
            name: ''
          },
          headImage:'',
          age:''
				},
        uploadVisible: false,
        failVisible: false,
        failList: [],

      }
		},
		methods: {
      beforeAvatarUpload(file) {
        const isXlsx = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        const isSizeLt10M = file.size / 1024 / 1024 < 10;
        if (!isXlsx) {
          this.$message.error('上传文件只能是 xlsx 格式!');
        }
        if (!isSizeLt10M) {
          this.$message.error('上传大小不能超过 10MB!');
        }
        return isXlsx && isSizeLt10M;
      },
      uploadSuccess(response) {
        if (response.success) {
          if (response.data.length) {
            this.failVisible = true;
            this.failList = response.data;
            console.log(this.failList)
          }
          this.$message.success(response.msg)
          this.uploadVisible = false;
        } else {
          this.$message.error(response.msg)
        }
        this.getEmployees()
      },
      download() {
        this.$http.post("/employee/download", this.search, {responseType: 'blob'})
            .then(response => {
              const fileUrl = URL.createObjectURL(new Blob([response.data]));
              const link = document.createElement('a');
              link.href = fileUrl;
              link.download = "用户信息表" + ".xlsx"; // 设置下载的文件名
              link.click(); // 模拟点击事件，触发文件下载
            })
            .catch(error => this.$message.error('网络异常: ' + error));
      },
      //导出
      downloadTemplate() {
        this.$http.post("/employee/download", [], {responseType: 'blob'})
            .then(response => {
              const fileUrl = URL.createObjectURL(new Blob([response.data]));
              const link = document.createElement('a');
              link.href = fileUrl;
              link.download = "用户信息表" + ".xlsx"; // 设置下载的文件名
              link.click(); // 模拟点击事件，触发文件下载
            })
            .catch(error => this.$message.error('网络异常: ' + error));
      },

		  //查询部门树
      getDeprTree(){
        this.$http.get("/dep/depTree")
            .then(res=>{
              console.log(res);
              res = res.data;
              console.log(res);
              if (res.success){
                this.deptTree=res.data
              }
            })
            .catch(res=>{})
      },
		  //获取所在部门
      getDepartment(){
          this.$http.get("/dep")
            .then(res=>{
              res = res.data;
              console.log(res);
              if (res.success){
                this.departments=res.data
              }
            })
            .catch(res=>{})
      },
		  //点击查询部门
      queryEmployees(){
        this.search.currentPage=1
        this.getEmployees()
      },
		  //每页条数变动
      handleSizeChange(val){
        this.search.pageSize = val
        this.getEmployees()
      },
		  //当前页
			handleCurrentChange(val) {
			  //val指的当前页
        this.search.currentPage=val
				// this.page = val;
				this.getEmployees();
			},
			//获取员工列表
			getEmployees() {
        this.listLoading=true;
				this.$http.post("/employee",this.search)
            .then(res=>{
              this.listLoading=false;
              res = res.data;
              console.log(res)
              if(res.success){
                // this.list = res.data.list
                // this.total= res.data.total
                this.pageInfo=res.data
              }
            })
            .catch(res=>{})
			},

			//根据id删除单个数据
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { id: row.id };
          console.log(row.id);
          this.$http.delete("/employee/"+row.id)
            .then(res=>{
              res = res.data;
              this.listLoading = false;
              if (res.success){
                this.$message({type:"success",message:"删除成功"})
              }else {
                this.$message.error("删除失败"+res.msg)
              }
              this.search.currentPage= 1;
              this.getEmployees();
            })
            .catch()
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
				this.saveForm = row;
				var split = row.path.split("/");
				var data = []
        for (let i = 1; i <split.length-1; i++) {
          data.push(Number.parseInt(split[i]))
        }
        console.log(data);
        this.saveForm.parent = data
        if (!row.parent){
				  this.saveForm.parent={
				    id:null,
				    username:''
          }
        }
        if (!row.manager){
          this.saveForm.manager={
            id:null,
            name:''
          }
        }
        this.getDepartment()
			},
			//显示新增界面
			handleAdd: function () {
				this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          username: '',
          email:'',
          department:{
            id: null,
            name: ''
          },
          headImage:'',
          age:''
				}
        this.getDepartment()

      },

			//编辑和新增保存信息
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							//NProgress.start();
							let para = Object.assign({}, this.saveForm);


							this.$http.put("/employee",para)
                .then(res=>{
                  this.saveFormVisible=false
                  this.$message({type:"success" ,message:"操作成功"})
                  this.getEmployees()
                })
                .catch(res=>{})
						});
					}
				});

			},
      inputSubmit(){
        // this.$refs.saveForm.validate((valid) => {
        //   if (valid) {
        //     this.$confirm('确认提交吗？', '提示', {}).then(() => {
        //       //NProgress.start();
        //       let para = Object.assign({}, this.saveForm);
        //
        //       this.$http.put("/employee",para)
        //           .then(res=>{
        //             this.saveFormVisible=false
        //             this.$message({type:"success" ,message:"操作成功"})
        //             this.getEmployees()
        //           })
        //           .catch(res=>{})
        //     });
        //   }
        // });
      },
			//新增
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {
					    this.listLoading = true;
              this.$http.patch("/employee",ids)
                  .then(res=>{
                    this.listLoading = false;
                    res = res.data;
                    if (res.success){
                      this.saveFormVisible=false
                      this.$message({message: '删除成功', type: 'success'});
                    }else {
                      this.saveFormVisible=false
                      this.$message.error("删除失败"+res.msg)
                    }
                    this.search.currentPage=1
                    this.getEmployees();
                  })
                  .catch(res=>{})
             })
				    .catch(() => {

            });
			}
		},
		mounted() {
			this.getEmployees();
			this.getDepartment()
		}
	}

</script>

<style scoped>

</style>


